﻿using System.Windows.Forms;
using System;
using System.ComponentModel;
using System.Data.OleDb;

namespace PictureOrganizer2.Forms
{
    public partial class AddAuthorForm : Form
    {

        public int AuthorId
        {
            get
            {
                return this.databaseDataSet.Author[0].ID;
            }
        }

        public AddAuthorForm()
        {
            InitializeComponent();

        }
        
        private void AddAuthorForm_Load(object sender, EventArgs e)
        {
            this.tb_AuthorName.Select();
        }
        
        private void tb_AuthorName_Validating(object sender, CancelEventArgs e)
        {
            string authorName = this.tb_AuthorName.Text;
            string errorMsg = string.Empty;
            if (String.IsNullOrWhiteSpace(authorName))
            {
                errorMsg = "Der Autorname darf nicht leer sein";
            }
            else if (this.authorTableAdapter.GetDataByAuthorName(authorName).Count > 0)
            {
                errorMsg = "Der angegebene Autor existiert bereits schon.";
            }

            if (!String.IsNullOrWhiteSpace(errorMsg))
            {
                errorProvider.SetError(this.tb_AuthorName, errorMsg);
                this.btn_Ok.Enabled = false;
            }
            else
            {
                errorProvider.Clear();
                this.databaseDataSet.Author.Clear();
                int nextId = Convert.ToInt32(this.authorTableAdapter.GetLastId() ?? 0) + 1;
                this.databaseDataSet.Author.AddAuthorRow(authorName, nextId);
                this.btn_Ok.Enabled = true;
            }
        }

        private void btn_Ok_Click(object sender, EventArgs e)
        {
            int i = this.authorTableAdapter.Update(this.databaseDataSet.Author);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
